# generate by ollama gpt-oss:20b

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pygame
import random
import sys

# --------------------- ① 设定常量 --------------------- #
SCREEN_WIDTH  = 600
SCREEN_HEIGHT = 600
CELL_SIZE     = 20          # 一个格子大小
FPS           = 10          # 初始速度（每秒帧数）
FONT_NAME     = None        # 系统默认字体

# 颜色定义（R, G, B）
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY  = (100, 100, 100)
GREEN = (0, 255, 0)
RED   = (255, 0, 0)
BLUE  = (0, 0, 255)

# --------------------- ② 初始化 pygame --------------------- #
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Snake - Press S to Start")
clock = pygame.time.Clock()

# 字体对象
font_big   = pygame.font.Font(FONT_NAME, 48)
font_small = pygame.font.Font(FONT_NAME, 24)

# --------------------- ③ 辅助函数 --------------------- #
def draw_text(text, font, color, surface, x, y, center=False):
    """在 surface 上绘制文字"""
    txt = font.render(text, True, color)
    rect = txt.get_rect()
    if center:
        rect.center = (x, y)
    else:
        rect.topleft = (x, y)
    surface.blit(txt, rect)

def random_food_position():
    """随机生成一个不与蛇身重叠的食物坐标"""
    while True:
        x = random.randint(0, (SCREEN_WIDTH  - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
        y = random.randint(0, (SCREEN_HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
        if (x, y) not in snake_body:
            return (x, y)

# --------------------- ④ 游戏主体变量 --------------------- #
snake_body = []          # 列表，存放蛇身每一节的 (x, y)
snake_dir  = (0, -1)     # 初始方向向上
food_pos   = None
score      = 0
game_over  = False
running    = True
started    = False      # 是否已开始（按 S 开始后为 True）

# --------------------- ⑤ 重置游戏 --------------------- #
def reset_game():
    global snake_body, snake_dir, food_pos, score, game_over, started
    snake_body = [(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)]
    snake_dir  = (0, -1)  # 向上
    food_pos   = random_food_position()
    score      = 0
    game_over  = False
    started    = True

# --------------------- ⑥ 主循环 --------------------- #
while running:
    clock.tick(FPS)

    # ---- 处理事件 ---- #
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 键盘事件
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_s:
                if not started:
                    reset_game()
                elif game_over:
                    reset_game()
            elif not game_over:
                # 方向键
                if event.key == pygame.K_UP and snake_dir != (0, 1):
                    snake_dir = (0, -1)
                elif event.key == pygame.K_DOWN and snake_dir != (0, -1):
                    snake_dir = (0, 1)
                elif event.key == pygame.K_LEFT and snake_dir != (1, 0):
                    snake_dir = (-1, 0)
                elif event.key == pygame.K_RIGHT and snake_dir != (-1, 0):
                    snake_dir = (1, 0)

    # ---- 更新游戏逻辑（仅在游戏已开始且未结束时） ---- #
    if started and not game_over:
        # 计算新头位置
        head_x, head_y = snake_body[0]
        dx, dy = snake_dir
        new_head = ((head_x + dx * CELL_SIZE) % SCREEN_WIDTH,
                    (head_y + dy * CELL_SIZE) % SCREEN_HEIGHT)

        # 检查自撞
        if new_head in snake_body:
            game_over = True
        else:
            snake_body.insert(0, new_head)  # 新头

            # 食物碰撞
            if new_head == food_pos:
                score += 1
                food_pos = random_food_position()
            else:
                snake_body.pop()  # 删除尾节

    # ---- 绘制 ---- #
    screen.fill(BLACK)

    # 绘制食物
    if food_pos:
        pygame.draw.rect(screen, RED,
                         (*food_pos, CELL_SIZE, CELL_SIZE))

    # 绘制蛇身
    for idx, (x, y) in enumerate(snake_body):
        color = GREEN if idx == 0 else BLUE
        pygame.draw.rect(screen, color,
                         (x, y, CELL_SIZE, CELL_SIZE))

    # UI 文本
    if not started:
        draw_text("Press S to Start", font_big, WHITE, screen,
                  SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, center=True)
    elif game_over:
        draw_text("Game Over", font_big, RED, screen,
                  SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 50, center=True)
        draw_text(f"Score: {score}", font_small, WHITE, screen,
                  SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 10, center=True)
        draw_text("Press S to Restart", font_small, WHITE, screen,
                  SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 40, center=True)
    else:
        # 运行中：显示分数
        draw_text(f"Score: {score}", font_small, WHITE, screen, 10, 10)

    # 更新显示
    pygame.display.flip()

# 退出
pygame.quit()
sys.exit()
